package com.example.ec.controller;

import com.example.ec.model.User;
import com.example.ec.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
@RequestMapping("user")
public class UserController extends BaseController{

    private final UserService userService;

    public UserController(UserService userService){
        this.userService = userService;
    }

    @PostMapping("create")
    private String create(User user){
        userService.create(user);
        return "redirect:/user/index.jsp";
    }

    @PostMapping("signIn")
    private String  signIn(User user){
        user = userService.queryOne("queryUsernamePasswordById",user);
        if(user == null){
            request.setAttribute("error","error Username and password.");
            return "redirect:/user/index.jsp";
        }
        session.setAttribute("user",user);
        if(user.getRole() == 0){
            return "redirect:/user/home.jsp";
        }else{
            session.setAttribute("users",userService.queryList("queryAllUsers",null));
            return "redirect:/admin.jsp";
        }
    }

    @GetMapping("queryById/{id}")
    private String queryById(@PathVariable("id") int id){
     session.setAttribute("user",userService.queryById(id));
     return "redirect:/user/edit.jsp";
    }

    @PostMapping("modify")
    private String modify(User user){
         userService.modify(user);
        session.setAttribute("users",userService.queryList("queryAllUsers",null));
         return "redirect:/admin.jsp";
    }

    @GetMapping("removeById/{id}")
    private String removeById(@PathVariable("id") int id){
        userService.removeById(id);
        session.setAttribute("users",userService.queryList("queryAllUsers",null));
        return "redirect:/admin.jsp";
    }


    @GetMapping("signOut")
    private String signOut(){
        session.invalidate();
        return "redirect:/";
    }


}
